package com.example.bankmanage.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.bankmanage.dto.rep.*;
import com.example.bankmanage.entity.PageBean;
import com.example.bankmanage.result.Result;
import com.example.bankmanage.service.AccountService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Date;
import java.time.LocalDate;

@SuppressWarnings("all")
@RestController
@RequestMapping("/account")
@Slf4j
public class AccountController {
    @Autowired
    private AccountService accountService;
    //accountNumber
    //accountType
    //page
    //size
    //status
    @GetMapping("/list")
    public Result<PageBean> fetchAccountList( @RequestParam(required = false) String accountNumber,@RequestParam(required = false) String accountType,@RequestParam Integer pageNum,@RequestParam Integer pageSize, @RequestParam(required =false) String status){
//        System.out.println(accountNumber + "   " +  accountType + "     " + status);
        PageBean pageBean = accountService.fetchAccountList(accountNumber,accountType,pageNum,pageSize,status);
        return Result.success(pageBean);
    }
    @PutMapping("/update")
    public Result updateAccount(@RequestParam Integer accountId, @RequestBody AccountUpdateReqDTO requestParam){
//        log.info("修改账户执行成功");
        accountService.updateAccount(accountId,requestParam);
        return Result.success();
    }
    @PostMapping("/add")
    public Result addAccount(@RequestBody AccountAddReqDTO requestParam){
        accountService.addAccount(requestParam);
        return Result.success();
    }
    @GetMapping("/detail")
    public Result getAccountDetail(@RequestParam Integer accountId){
        GetAccountDetailReqDTO requestParam =  accountService.getAccountDetail(accountId);
        return Result.success(requestParam);
    }
    @GetMapping("/exportBill")
    public void exportAccount(@RequestParam(required = false) String accountNumber,@RequestParam(required = false) String accountType,
                              @RequestParam(required = false) String status,@RequestParam(required = false) String startDate,
                              @RequestParam(required = false) String endDate, HttpServletResponse response)throws IOException {
        log.info("导出参数: accountNumber={}, accountType={}, status={}",
                accountNumber, accountType, status);

        // 关键修改1: 确保在异常时重置response
        response.reset();

        try {
            // 1. 构建查询参数
            AccountExportReqDTO exportDTO = new AccountExportReqDTO();
            exportDTO.setAccountNumber(accountNumber);
            exportDTO.setAccountType(accountType);
            exportDTO.setStatus(status);

            // 日期转换处理
            if (StringUtils.isNotBlank(startDate)) {
                try {
                    exportDTO.setStartDate(Date.valueOf(startDate));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("开始日期格式不正确，应为YYYY-MM-DD");
                }
            }
            if (StringUtils.isNotBlank(endDate)) {
                try {
                    exportDTO.setEndDate(Date.valueOf(endDate));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("结束日期格式不正确，应为YYYY-MM-DD");
                }
            }

            // 2. 设置响应头
            String fileName = "账单_" + LocalDate.now() + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 3. 导出Excel
            accountService.exportAccount(exportDTO, response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            log.error("导出Excel失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write(JSON.toJSONString(Result.error("导出失败: " + e.getMessage())));
        }
    }
}
